﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.StorageClient;
using Smarly.Ebook.Model;
using Smarly.Web.Areas.Profile.Helpers;
using Smarly.Web.Controllers.Base;
using CloudBlobClient = Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient;
using CloudBlobContainer = Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer;

namespace Smarly.Web.Areas.Profile.Controllers
{
	public class EbookController : AuthBaseController
	{
		static readonly CloudBlobContainer container;

		static EbookController()
		{
			CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureStorageConnectionString"].ConnectionString);
			CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
			container = blobClient.GetContainerReference("ebooks");
			container.CreateIfNotExists();
		}

		public ActionResult Index(string parts)
		{
			var chapterHash = "/" + parts.Substring(0, parts.Length - ("." + RouteData.Values["extention"]).Length);
			ProfileEbook model = new ProfileEbook().Get(UserIdentity, chapterHash);
			return View(model);
		}

		public ActionResult Download(string parts)
		{
			var chapterHash = "/" + parts.Substring(0, parts.Length - ("." + RouteData.Values["extention"]).Length);
			ProfileEbook model = new ProfileEbook().Get(UserIdentity, chapterHash);

			if (!string.IsNullOrWhiteSpace(model.EbookUrl))
			{
				ICloudBlob blob = container.GetBlobReferenceFromServer(model.EbookUrl);
				using (MemoryStream ms = new MemoryStream())
				{
					blob.DownloadToStream(ms);
					ms.Flush();
					ms.Position = 0;

					return File(ms.GetBuffer(), "application/pdf", model.EbookUrl);
				}
			}

			return Redirect(Url.EbookDownload(model.CurrentBook.HashTag));
		}

	}

}
